define(function(require) {

  var _ = require('underscore');
  var Backbone = require('backbone');
  var loader = require('./loader');
  var PageView = require('./pages/PageView');
  //
  // app: app model (from app.js)
  var Application = function(model, options) {

    this.model = model;
    this.options = options;

    this.initialize.apply(this, arguments);
  };

  _.extend(Application.prototype, Backbone.Events, {

    initialize: function(){},

    launch: function() {

      this._initCollections();
      loader.createRootPage( this.getPageId() )
      .then(function(page){
        this.rootPage = page;
        // 渲染页面
        page.render().$el.appendTo(document.body);

        this._initRouter();

        // 通知factory，页面已加载完成
        window.dispatchEvent( new CustomEvent('application:load', {
          detail: {application: this}
        }) );
      }.bind(this));
    },

    _initRouter: function(){
      var Router = Backbone.Router.extend({
        routes: {
          "*path(?*queryString)": "any"
        }
      });
      var router = new Router();
      this.listenTo(router, 'route:any', this.route);

      // launch history
      var pathname = window.location.pathname;
      var rootPath = pathname;//.substr(0, pathname.lastIndexOf('/'));
      Backbone.history.start({pushState: false, root: rootPath});
      console.log("start history with root: [%s]", rootPath);
    },

    route: function(path, queryString){
      this.rootPage.route && this.rootPage.route(path, queryString);
    },

    // 从URL路径获取要访问的页面ID
    getPageId: function(){
      // 从URL获取页面ID，例如index.html则页面ID为index，register.html则ID为register
      var page_id = _.last(window.location.pathname.split('/')).replace(".html", "");

      // 如果page_id为index，且存在defaultPage配置，则ID为defaultPage属性的值
      // 如果page_id为index，但不存在defaultPage配置，则ID为index
      // 如果page_id不为index，则还是原来的值
      page_id = (page_id == 'index') ? (window.app.defaultPage || 'index') : page_id;
      return page_id;
    },
    // FIXME cann't make sure custom collection has been loaded yet
    _initCollections: function() {
      var collections = window.app.collections;
      for (var key in collections) {
        _Collection = require('./models/' + collections[key].type);
        if (_Collection) {
          this.collectionPool[key] = new _Collection([], null, collections[key]);
        }
      }
    },

    collectionPool: {},

    getCollection: function(name, models) {
      var collection = this.collectionPool[name];
      if (!collection) {
        var _Collection = library.getCollection(name);
        if (_Collection) {
          collection = this.collectionPool[name] = new _Collection;
        }
      }
      if (models)
        collection.models = models;
      return collection;
    },

  });


  Application.extend = Backbone.Model.extend;
  return Application;
});
